// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// a [author] rhyme_lph
// C [email]  rhymelph@gmail.com
// O [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/entities/debit_note_detail_entity.dart';
import 'package:finance_app/src/provider/dashboard/debit_note/delete_debit_note_provider.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/reg_exp_utils.dart';
import 'package:finance_app/src/widgets/button/normal_float_text_button.dart';
import 'package:finance_app/src/widgets/button/normal_float_text_white_button.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:finance_app/src/widgets/select/credit_note_number_radio.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:tuple/tuple.dart';

@RouterMeta(paramName: "DeleteDebitNotePage")
class DeleteDebitNotePage extends StatefulWidget {
  @override
  _DeleteDebitNotePageState createState() => _DeleteDebitNotePageState();
}

class _DeleteDebitNotePageState extends State<DeleteDebitNotePage>
    with PagePresenter<DeleteDebitNotePage, DeleteDebitNoteProvider> {
  @override
  PreferredSizeWidget get appBar =>
      getDefaultAppBar(title: S.current.delete + ' ' + S.current.debit_note);

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: Stack(
          children: [
            Column(
              children: [
                AppSpaces.h20,
                SearchInputField(
                  controller: provider.searchController,
                  focusNode: provider.searchFocusNode,
                ),
                AppSpaces.h20,
                Expanded(
                  child: listBuilder<String>(
                    selector: (_, __) => __.searchController.text,
                    builder:
                        (BuildContext context, String value, Widget child) =>
                            ListView(
                      children: buildSearchWidget(value),
                    ),
                  ),
                ),
              ],
            ),
            Positioned(
                bottom: getDp(32) + MediaQuery.of(context).padding.bottom,
                left: 0.0,
                right: 0.0,
                child: _buildBottomBar()),
          ],
        ),
      );

  Widget _buildBottomBar() => Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          NormalFloatTextWhiteButton(
            title: S.current.cancel,
            onTap: provider.onCancel,
          ),
          SizedBox(
            width: getDp(15),
          ),
          NormalFloatTextButton(
            title: S.current.delete,
            onTap: provider.onDelete,
          ),
        ],
      );

  List<Widget> buildSearchWidget(String value) {
    List<Widget> slivers;
    if (provider.searchController.text.isNotEmpty) {
      slivers = provider.data
          .toList()
          .where(_onSearchInputGroup)
          .map((e) => buildSliverItem(e))
          .toList();
    } else {
      slivers = provider.data.toList().map(buildSliverItem).toList();
    }
    return slivers;
  }

  Widget buildSliverItem(DebitNoteDetailEntity data) {
    return listBuilder<Tuple2<DebitNoteDetailEntity, bool>>(
      selector: (_, __) => Tuple2(
          data,
          __.currentSelectList.firstWhere((element) => element.id == data.id,
                  orElse: () => null) !=
              null),
      builder: (BuildContext context, Tuple2<DebitNoteDetailEntity, bool> value,
              Widget child) =>
          PressedOpacityButton(
        onPressed: () => provider.onSelect(value.item1),
        child: CreditNoteNumberCheckBox(
          title: value.item1.contact.name,
          creditNoteNo: value.item1.number,
          issueDate: DateTimeUtils.formatDateTimeString(value.item1.issuedAt),
          amount: value.item1.total?.toDouble(),
          currency: value.item1.currencyCode,
          isSelect: value.item2,
        ),
      ),
    );
  }

  Widget buildSliverHeader({String title}) {
    final String _title = title.isEmpty ? "*" : title;
    return ListHeaderItem(
      title: _title,
    );
  }

  bool _onSearchInputGroup(DebitNoteDetailEntity element) {
    String searchInput = provider.searchController.text;
    return RegExpUtils.getSearchRegExp(searchInput)
        .hasMatch(element.contact.name);
  }
}
